import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hive/hive.dart';

import '../../api/api_client.dart';
import '../../models/user.dart';
import 'auth_event.dart';
import 'auth_state.dart';


class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final ApiClient apiClient;
  final Box<User> userBox;

  AuthBloc({required this.apiClient, required this.userBox}) : super(AuthInitial()) {
    on<AppStarted>(_onAppStarted);
    on<LoginButtonPressed>(_onLoginButtonPressed);
    on<LogoutButtonPressed>(_onLogoutButtonPressed);
    on<GetCodePressed>(_onGetCodePressed);
    on<AuthLogoutPress>(_onLogotPressed);
  }

  FutureOr<void> _onLogotPressed(AuthLogoutPress event, Emitter<AuthState> emit) async {
    try {
      // Clear user from Hive
      await userBox.delete('currentUser');
      emit(AuthUnauthenticated());
    } catch (e) {
    }
  }



  void _onAppStarted(AppStarted event, Emitter<AuthState> emit) {
    // Check if user is already logged in by looking in Hive
    final user = userBox.get('currentUser');
    if (user != null) {
      emit(AuthAuthenticated(user));
    } else {
      emit(AuthUnauthenticated());
    }
  }

  Future<void> _onLoginButtonPressed(LoginButtonPressed event, Emitter<AuthState> emit) async {
    emit(AuthLoading());
    try {
      final user = await apiClient.login(event.phone, event.code);
      // Save user to Hive
      if(user.isSuccessful  && user?.data  != null) {
        await userBox.put('currentUser', user!.data!);
        emit(AuthAuthenticated(user!.data!));
      }else {
        emit(AuthFailure(user?.message ?? '登录失败，请重试'));
      }
    } catch (e) {
      print(e);
      emit(AuthFailure(e.toString()));
    }
  }

  Future<void> _onGetCodePressed(GetCodePressed event, Emitter<AuthState> emit) async {
    emit(AuthLoading());
    try {
      final code = await apiClient.sendCode(event.phone);
      // Save user to Hive
      if(code.isSuccessful) {
        emit(AuthCode(code.message ?? '验证码发送成功'));
      }else {
        emit(AuthFailure(code.message ?? '验证码发送失败，请重试'));
      }
    } catch (e) {
      print(e);
      emit(AuthFailure(e.toString()));
    }
  }

  Future<void> _onLogoutButtonPressed(LogoutButtonPressed event, Emitter<AuthState> emit) async {
    emit(AuthLoading());
    // Clear user from Hive
    await userBox.delete('currentUser');
    emit(AuthUnauthenticated());
  }


}